<template>
  <div class="game-page" v-if="!piniaSystem.getIsH5">
    <div class="game-page-header">
      <h2 class="game-page-header__title">{{pageName}}</h2>
      <div class="game-page-header__filter">
        <el-form :model="form" class="form-size-small item-not-margin-top" inline>
          <el-form-item :label="t('home.sort')">
            <el-select v-model="form.sort" @change="sortHallGame">
              <el-option label="A-Z" value="AZ" />
              <el-option label="Z-A" value="ZA" />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('home.platform')">
            <el-select v-model="form.gameChannel" clearable @change="queryData" :placeholder="t('userInfo.text1')">
              <el-option :label="item.gameChannelName" :value="item.gameChannel" v-for="item in options" :key="item.gameChannel">
                <span style="float: left">{{ item.gameChannelName }}</span>
                <span style="float: right;">{{ item.gameNum }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <ul class="game-content-list">
      <li v-for="game in hallGame" :key="game.id" @click="gotoPlay(game)">
        <img v-zlazy="game.imgPlay" alt="">
        <h3>
          <span>{{game.name}}</span>
          <el-popover
            placement="top"
            trigger="click"
            popper-class="z-card-tips"
          >
            <template #reference>
              <em @click.stop><i-ep-warning /></em>
            </template>
            <div class="z-card-tips__content">
              <div class="z-card-tips__box">
                <em>RTP</em>
                <span>{{game.gameRtp}}%</span>
              </div>
              <div class="z-card-tips__title">{{game.gameChannelName}}</div>
            </div>
          </el-popover>
        </h3>
      </li>
    </ul>
    <ZPagination
      class="game-pagination"
      v-model:pagination="pagination"
      :query="queryData"
    />
  </div>
  <div class="game-page-h5" v-if="piniaSystem.getIsH5">
    <ZScroll fixed>
      <span
        v-for="item in options"
        :class="{'active': form.gameChannel == item.gameChannel}"
        @click="handleScrollTabs(item)"
      >
      {{ item.gameChannelName || `All` }}·({{ item.gameNum }})
      </span>
    </ZScroll>
    <div class="game-page-h5_box">
      <ul
        class="game-content-list"
      >
        <li v-for="game in hallGame" :key="game.id" @click="gotoPlay(game)">
          <div class="game-content-li-p5">
            <img v-zlazy="game.imgPlay" alt="">
            <h3>
              <span>{{game.name}}</span>
              <el-popover
                placement="top"
                trigger="click"
                popper-class="z-card-tips"
              >
                <template #reference>
                  <em @click.stop><i-ep-warning /></em>
                </template>
                <div class="z-card-tips__content">
                  <div class="z-card-tips__box">
                    <em>RTP</em>
                    <span>{{game.gameRtp}}%</span>
                  </div>
                  <div class="z-card-tips__title">{{game.gameChannelName}}</div>
                </div>
              </el-popover>
            </h3>
          </div>
        </li>
      </ul>
      <!-- <div class="" v-if="loadmoreDone">没有更多了</div>
      <div class="" v-else>加载中</div> -->
    </div>
  </div>
  <TipsRecharge v-model:visible="showTipsRecharge"/>
</template>

<script setup lang="ts">
import gamesApi from '@/api/modules/games';
import system from '@/store/system';
import nocache from '@/store/nocache';
import userinfo from '@/store/userinfo';

const { t } = useI18n();
const piniaSystem = system();
const piniaNocache = nocache();
const piniaUserinfo = userinfo();
const router = useRouter();
const route = useRoute();
const currentWallet: any = computed(()=> piniaUserinfo.getCurrentWallet);

const whichPopupType = computed(()=>{
  return piniaSystem.getIsH5 ?
    markRaw(defineAsyncComponent(() => import('vant/es/popup'))) :
    markRaw(defineAsyncComponent(() => import('@/components/Dialog/index.vue')));
});

const props = defineProps({
  gameType: {
    type: Number,
    default: 0
  },
  pageName: {
    type: String,
    default: ""
  }
});

const data: any = reactive({
  form: {
    sort: 'AZ',
    gameChannel: ''
  },
  pagination: {
    total: 0,
    pageSize: 30,
    pageNum: 1
  },
  options: [],
  hallGame: [],
  loadmoreDone: false,
  showTipsRecharge: false
});

const {
  form,
  pagination,
  options,
  hallGame,
  loadmoreDone,
  showTipsRecharge,
} = toRefs(data);

// 监听语言切换
watch(
  () => piniaSystem.getLang.code,
  (val, preVal) => {
    handleLangName();
  },
  { immediate: false, deep: true },
);

// 监听触底
watch(
  () => piniaNocache.getHitBottom,
  (val, preVal) => {
    piniaSystem.getIsH5 && loadmore();
  },
  { immediate: false, deep: true },
);

// 排序
const sortHallGame = () => {
  if(form.value.sort === 'AZ'){
    // 正序
    hallGame.value.sort((a:any, b:any)=>
      +(a.gameName.toLowerCase() > b.gameName.toLowerCase()) || +(a.gameName.toLowerCase() === b.gameName.toLowerCase()) - 1
    );
  }else if(form.value.sort === 'ZA'){
    // 倒序
    hallGame.value.sort((a:any, b:any)=>
      +(a.gameName.toLowerCase() < b.gameName.toLowerCase()) || +(a.gameName.toLowerCase() === b.gameName.toLowerCase()) - 1
    );
  }
}

// 名称语言显示
const handleLangName = () => {
  // 切换一个语言
  hallGame.value.map((im:any)=>{
    const item = im.languageChildren.find((ele:any)=>{
      return ele.languageType == piniaSystem.getLang.code;
    })
    im.name = item.languageName || im.gameName || "-";
  })
}

// 游戏平台下拉
const getPlayBaseGameChannel = () => {
  gamesApi.getPlayBaseGameChannel({
    gameType: props.gameType || 0
  }).then((response: any)=>{
    if(response.code === 200){
      options.value = response.data || [];
      options.value.unshift({
        gameChannel: "",
        gameChannelName: computed(()=>t('BetRecord.All')),
        gameNum: options.value.reduce((item:any, next:any)=> item + next.gameNum, 0)
      });
    }
  });
}
getPlayBaseGameChannel();

// 请求数据
const queryData = () => {
  piniaNocache.setLoading(true);
  gamesApi.getAllGameList({
    gameChannel: form.value.gameChannel,
    gameType: props.gameType,
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
  }).then((response:any)=>{
    if(response.code === 200){
      pagination.value.total = response.data.total || 0;
      if(piniaSystem.getIsH5){
        hallGame.value = [...hallGame.value, ...(response.data.hallGame || [])];
      }else{
        hallGame.value = response.data.hallGame || [];
      }
      sortHallGame();
      handleLangName();
    }
  }).finally(()=>{
    piniaNocache.setLoading(false);
  });
}
queryData();

// 滚动tab切换
const handleScrollTabs = (item:any) => {
  form.value.gameChannel = item.gameChannel;
  pagination.value.pageNum = 1;
  loadmoreDone.value = false;
  hallGame.value = [];
  queryData();
}

// 上拉加载
const loadmore = () => {
  console.log('总页数', Math.ceil(pagination.value.total / pagination.value.pageSize))
  if(pagination.value.pageNum >= Math.ceil(pagination.value.total / pagination.value.pageSize)){
    loadmoreDone.value = true;
    return false;
  }else{
    pagination.value.pageNum ++;
    queryData();
  }
}

// 点击玩游戏
const gotoPlay = (game: any) => {
  if(piniaUserinfo.getHaslogged){
    // 已经登录
    if(game.gameId && game.gameId.trim()){
      const data = {
        playId: game.playId,
        imgPlay: game.imgPlay,
        gameName: game.gameName,
        fromPath: route.fullPath,
      }
      if(currentWallet.value.money > 0){
        router.replace({
          path: '/playbox',
          query: data
        });
      }else{
        showTipsRecharge.value = true;
      }
    }
  }else{
    // 未登录
    piniaNocache.openLogin();
  }
}

onBeforeMount(()=>{
  piniaNocache.setHideFooterBar(true);
});

onUnmounted(()=>{
  piniaNocache.setHideFooterBar(false);
});
</script>

<style lang="scss" scoped>
@import url(./index.scss);
</style>
